import React, { useState, useEffect } from 'react';
import { Breadcrumb as AntBreadcrumb } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { useLocation, Link } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { root } from '@/router/router.config';
import { IRouter } from '@/router/router.d';
import { RootState } from '@/store';

// 查询路由配置表 并返回每个面包屑的路由配置
const querySelectRouteConf = (pathname: string, flattenRouters: IRouter[]): IRouter[] => {
  let res: IRouter[] = [];
  let matching: string[] = pathname.split('/');
  
  matching.forEach((item, index) => {
    let count = -1;
    let currentPaht = '';

    while (count !== index) {
      count ++;
      currentPaht += matching[count] ? `/${matching[count]}` : '';
    }
    
    const currentRoute = flattenRouters.find(route => route.path === currentPaht && route.meta?.title && route.meta.breadcrumb !== false);
    if (currentRoute) {
      res.push(currentRoute)
    }
  })
  
  return res;
}

const Breadcrumb = () => {
  // 授权后的router
  const flattenRouters: IRouter[] = useSelector((state: RootState) => state.global.flattenRouters);
  const { pathname } = useLocation<string>();

  // 面包屑
  const [breadcrumbData, setBreadcrumbData] = useState<IRouter[]>([]);
  useEffect(() => {
    setBreadcrumbData(querySelectRouteConf(pathname, flattenRouters));
  }, [flattenRouters])
  return (
    <AntBreadcrumb>
      <AntBreadcrumb.Item>
        <Link to={root}><HomeOutlined /></Link>
      </AntBreadcrumb.Item>
      {
        breadcrumbData.map(item => <AntBreadcrumb.Item key={item.path}>
          {/* {item.meta?.icon} */}
          {/* {item.path !== pathname ? <Link to={item.path}>{item.meta?.title}</Link> : <span>{item.meta?.title}</span>} */}
          
          {<span>{item.meta?.title}</span>}
        </AntBreadcrumb.Item>)
      }
    </AntBreadcrumb>
  )
}

export default Breadcrumb;
